package com.dwaynema.controller;

import com.dwaynema.common.RestResult;
import com.dwaynema.common.RestResultEnum;
import com.dwaynema.common.Result;
import com.dwaynema.dto.ArticleDto;
import com.dwaynema.entity.Article;
import com.dwaynema.service.ArticleService;
import com.dwaynema.util.RestResultUtil;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/article")
public class ArticleController {
    Result restResult;

    @Autowired
    ArticleService articleService;

    @PostMapping("/add")
    @ResponseBody
    @RequiresAuthentication
    public RestResult addArticle(@Valid Article article, BindingResult result){
        if(result.hasErrors()){
            restResult= new Result();
            restResult.setCode("error");
            restResult.setDefaultMessage("数据错误");
            return RestResultUtil.result(RestResultEnum.ERROR,"请求失败",restResult);
        }
        Integer add=articleService.addArticle(article);
        if(add>0){
            return RestResultUtil.result(RestResultEnum.SUCCESS,"创建成功",null);
        }else {
            return RestResultUtil.result(RestResultEnum.ERROR,"创建失败",null);
        }
    }

    @GetMapping("/articles")
    @ResponseBody
    public RestResult getArticles(){
        List<ArticleDto> articleDto;
        articleDto=articleService.getArticles();
        if(articleDto.isEmpty()){
            restResult=new Result();
            return RestResultUtil.result(RestResultEnum.ERROR,"无数据",null);
        }
        return RestResultUtil.result(RestResultEnum.SUCCESS,"请求成功",articleDto);
    }

    @GetMapping("/article/{id}")
    @ResponseBody
    public RestResult getArticleById(@PathVariable("id") String id){
        Integer ids=Integer.parseInt(id);
        ArticleDto articleDto=articleService.getArticleById(ids);
        if(articleDto==null){
            restResult=new Result();
            return RestResultUtil.result(RestResultEnum.ERROR,"无数据",null);
        }
        return RestResultUtil.result(RestResultEnum.SUCCESS,"请求成功",articleDto);
    }
}
